﻿


CREATE PROCEDURE [dbo].[RDIFramework_CiItems_DELETE]
(
	@id int	 = null
   ,@ModifiedOn datetime = NULL
   ,@ModifyUserId nvarchar(50) = NULL
   ,@ModifiedBy nvarchar(50)  = NULL
   ,@OperationType nvarchar(30)             --DELETE:物理删除数据、SETDELMARK:逻辑删除数据
   ,@SuccessMark INT = 0 OUTPUT		        --成功标志 >0：操作成功 <=0,操作失败
   ,@ReturnInfo nvarchar(500) = '' OUTPUT   --操作提示信息 

)
AS
BEGIN
	SET NOCOUNT ON
	IF @OperationType IS NULL
	BEGIN
		RAISERROR ( '操作类型不能为空！', 16, 1 )
		SELECT @ReturnInfo =  '操作类型不能为空！'
		SELECT @SuccessMark = 0
		ROLLBACK TRAN
		RETURN
	END	

	IF @Id IS NULL
	BEGIN
		RAISERROR ( '主键为空！', 16, 1 )
		SELECT @ReturnInfo =  '主键为空！'
		SELECT @SuccessMark = 0
		ROLLBACK TRAN
	END
	
	
	--1、物理删除指定数据
	IF @OperationType = 'DELETE' --物理删除数据
	BEGIN
		BEGIN TRAN
		DELETE FROM dbo.CiItems WHERE Id = @Id	
		DELETE FROM dbo.CiItemDetails WHERE ItemId = @id --同时删除字典明细项
			
		IF @@ROWCOUNT > 0 AND @@ERROR=0    
	    BEGIN 
			SELECT @ReturnInfo='成功删除指定数据字典！'
			SELECT @SuccessMark = 1      
			COMMIT TRAN
			RETURN
	    END    
		ELSE
		BEGIN
			SELECT @ReturnInfo='删除指定数据字典失败！'
			SELECT @SuccessMark = 0
			ROLLBACK TRAN
			RETURN
		END 
	END
	
	--2、逻辑删除指定数据
	IF @OperationType = 'SETDELMARK' --逻辑删除数据[置删除标记]
	BEGIN
		DECLARE @DELETEROWSCOUNT INT = 0
		BEGIN TRAN
		IF @ModifyUserId IS NULL OR @ModifiedBy IS NULL
		BEGIN
			SELECT @ModifyUserId = ModifyUserId,@ModifiedBy = ModifiedBy FROM dbo.CiItems
			WHERE Id = @Id
		END
		
		UPDATE dbo.CiItems
		SET DeleteMark = 1,ModifiedOn = GETDATE(),ModifyUserId = @ModifyUserId,ModifiedBy = @ModifiedBy
		WHERE Id = @Id
		SELECT @DELETEROWSCOUNT = @DELETEROWSCOUNT + @@ROWCOUNT
		
		--同步更新字典明细项
		UPDATE dbo.CiItemDetails
		SET DeleteMark = 1,ModifiedOn = GETDATE(),ModifyUserId = @ModifyUserId,ModifiedBy = @ModifiedBy
		WHERE ItemId = @Id
		SELECT @DELETEROWSCOUNT = @DELETEROWSCOUNT + @@ROWCOUNT
		
		IF @@ROWCOUNT >= 1 AND @@ERROR=0    
	    BEGIN 
			SELECT @ReturnInfo='成功删除指定数据字典！'  
			SELECT @SuccessMark = 1   
			COMMIT TRAN
			RETURN
	    END    
		ELSE
		BEGIN
			SELECT @ReturnInfo='删除指定数据字典失败！'
			SELECT @SuccessMark = 0
			ROLLBACK TRAN
			RETURN
		END 		
	END
	
END


